import 'package:stacked/stacked.dart';
import '../heartbeat/blueprint/checkin_model.dart';

/// 打卡追踪器
class CheckinTracker extends BaseViewModel {
  // 打卡记录列表（模拟数据库）
  final List<CheckinRecordModel> _records = [];

  /// 获取所有打卡记录
  List<CheckinRecordModel> get records => List.from(_records);

  /// 初始化默认打卡数据
  void initializeDefaultCheckins() {
    _records.clear();
    _records.addAll(_getDefaultCheckins());
  }

  /// 获取默认打卡数据
  List<CheckinRecordModel> _getDefaultCheckins() {
    return [
      // admin用户（ID: 1）的打卡记录
      CheckinRecordModel(
        id: '1',
        userId: '1',
        date: DateTime.now().subtract(const Duration(days: 7)),
        isChecked: true,
      ),
      CheckinRecordModel(
        id: '2',
        userId: '1',
        date: DateTime.now().subtract(const Duration(days: 6)),
        isChecked: true,
      ),
      CheckinRecordModel(
        id: '3',
        userId: '1',
        date: DateTime.now().subtract(const Duration(days: 5)),
        isChecked: false,
      ),
      CheckinRecordModel(
        id: '4',
        userId: '1',
        date: DateTime.now().subtract(const Duration(days: 4)),
        isChecked: true,
      ),
      CheckinRecordModel(
        id: '5',
        userId: '1',
        date: DateTime.now().subtract(const Duration(days: 3)),
        isChecked: true,
      ),
      CheckinRecordModel(
        id: '6',
        userId: '1',
        date: DateTime.now().subtract(const Duration(days: 2)),
        isChecked: false,
      ),
      CheckinRecordModel(
        id: '7',
        userId: '1',
        date: DateTime.now().subtract(const Duration(days: 1)),
        isChecked: true,
      ),
    ];
  }

  /// 执行打卡
  Future<bool> executeCheckin(String userId) async {
    setBusy(true);
    try {
      final today = DateTime.now();
      final todayString = DateTime(today.year, today.month, today.day);

      // 检查今天是否已经打卡
      final existingRecord = _records.firstWhere(
        (record) =>
            record.userId == userId &&
            DateTime(record.date.year, record.date.month, record.date.day) ==
                todayString,
        orElse:
            () => CheckinRecordModel(
              id: '',
              userId: '',
              date: DateTime.now(),
              isChecked: false,
            ),
      );

      if (existingRecord.id.isNotEmpty && existingRecord.isChecked) {
        setError('You have already checked in today');
        return false;
      }

      // 创建或更新打卡记录
      if (existingRecord.id.isEmpty) {
        // 创建新记录
        final newRecord = CheckinRecordModel(
          id: DateTime.now().millisecondsSinceEpoch.toString(),
          userId: userId,
          date: today,
          isChecked: true,
        );
        _records.add(newRecord);
      } else {
        // 更新现有记录
        final recordIndex = _records.indexWhere(
          (r) => r.id == existingRecord.id,
        );
        if (recordIndex != -1) {
          _records[recordIndex] = existingRecord.copyWith(isChecked: true);
        }
      }

      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 取消打卡
  Future<bool> revokeCheckin(String userId) async {
    setBusy(true);
    try {
      final today = DateTime.now();
      final todayString = DateTime(today.year, today.month, today.day);

      // 查找今天的打卡记录
      final recordIndex = _records.indexWhere(
        (record) =>
            record.userId == userId &&
            DateTime(record.date.year, record.date.month, record.date.day) ==
                todayString,
      );

      if (recordIndex == -1) {
        setError('No check-in record found for today');
        return false;
      }

      // 更新记录为未打卡
      _records[recordIndex] = _records[recordIndex].copyWith(isChecked: false);

      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 获取用户的打卡记录
  List<CheckinRecordModel> fetchUserCheckins(String userId) {
    return _records.where((record) => record.userId == userId).toList()
      ..sort((a, b) => b.date.compareTo(a.date));
  }

  /// 获取用户指定日期的打卡状态
  bool? getUserCheckinStatus(String userId, DateTime date) {
    final targetDate = DateTime(date.year, date.month, date.day);

    try {
      final record = _records.firstWhere(
        (record) =>
            record.userId == userId &&
            DateTime(record.date.year, record.date.month, record.date.day) ==
                targetDate,
      );
      return record.isChecked;
    } catch (e) {
      return null; // 没有记录
    }
  }

  /// 检查用户今天是否已打卡
  bool hasUserCheckedInToday(String userId) {
    final today = DateTime.now();
    final todayString = DateTime(today.year, today.month, today.day);

    return _records.any(
      (record) =>
          record.userId == userId &&
          DateTime(record.date.year, record.date.month, record.date.day) ==
              todayString &&
          record.isChecked,
    );
  }

  /// 获取用户本月打卡统计
  Map<String, dynamic> calculateMonthlyStats(String userId) {
    final now = DateTime.now();
    final monthStart = DateTime(now.year, now.month, 1);
    final monthEnd = DateTime(now.year, now.month + 1, 0);

    final monthlyRecords =
        _records.where((record) {
          if (record.userId != userId) return false;
          final recordDate = DateTime(
            record.date.year,
            record.date.month,
            record.date.day,
          );
          return recordDate.isAfter(
                monthStart.subtract(const Duration(days: 1)),
              ) &&
              recordDate.isBefore(monthEnd.add(const Duration(days: 1)));
        }).toList();

    final checkedInDays = monthlyRecords.where((r) => r.isChecked).length;
    final totalDays = now.day; // 当前月份已过去的天数

    return {
      'totalDays': totalDays,
      'checkedInDays': checkedInDays,
      'missedDays': totalDays - checkedInDays,
      'checkinRate':
          totalDays > 0 ? (checkedInDays / totalDays * 100).round() : 0,
    };
  }

  /// 获取用户打卡历史（按月份分组）
  Map<String, List<CheckinRecordModel>> getCheckinHistoryByMonth(
    String userId,
  ) {
    final userRecords = fetchUserCheckins(userId);
    final Map<String, List<CheckinRecordModel>> history = {};

    for (final record in userRecords) {
      final monthKey =
          '${record.date.year}-${record.date.month.toString().padLeft(2, '0')}';
      if (!history.containsKey(monthKey)) {
        history[monthKey] = [];
      }
      history[monthKey]!.add(record);
    }

    return history;
  }
}
